package com.flx.noodle.websocket.handler;

import com.flx.noodle.websocket.adapter.ChatSessionAdapter;
import com.flx.noodle.websocket.entity.SSOUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;
import util.WsConstant;

/**
 * Created by fenglixiong on 2017/10/2.
 */
@Component
public class ChatHandler extends AbstractWebSocketHandler{

    protected final Log logger = LogFactory.getLog(getClass());

    @Autowired
    protected ChatSessionAdapter adapter;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        logger.info("afterConnectionEstablished:" + session.getId() + "\tsession:" + session.getAttributes().size());
        super.afterConnectionEstablished(session);
        try {
            SSOUser ssoUser = (SSOUser)session.getAttributes().get(WsConstant.WEBSOCKET_SESSION_KEY);
            //这里是给手机用的，手机端会把chatid直接放到header里面传过来
            String chatSid = (String) session.getAttributes().get(WsConstant.HEADER_CHAT_ROOMID);
            if (ssoUser != null&& StringUtils.isNotBlank(chatSid)) {
                logger.info("begin to addSession user [" + ssoUser.getUserName() + "] has connected");
                adapter.addUserSession(ssoUser, Integer.parseInt(chatSid), session);
            } else {
                logger.info("user session null!");
            }
        }catch (Exception e){
            logger.info("【异常-建立连接】[ChatHandler][afterConnectionEstablished]建立连接时候出现了异常："+e);
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        logger.info("[ChatHander]start close session!" + session.getId() + "\t" + session.isOpen() + "\tclients:" + adapter);
        try {
            SSOUser ssoUser = (SSOUser)session.getAttributes().get(WsConstant.WEBSOCKET_SESSION_KEY);
            if (ssoUser != null) {
                this.adapter.removeSession(ssoUser.getUserId(), ssoUser.getChatId(), session.getId());
            }
            logger.info("[ChatHandler]end close session!");
        }catch (Exception e){
            logger.info("【异常-连接关闭】[ChatHandler][afterConnectionClosed]发生了异常："+e);
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        logger.info("handleTransportError:" + session.getId() + "\tmessage:" + exception.getMessage());
        exception.printStackTrace();
        super.handleTransportError(session, exception);
    }

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String msg = message.getPayload();
        SSOUser ssoUser = (SSOUser)session.getAttributes().get(WsConstant.WEBSOCKET_SESSION_KEY);
        logger.info("handleTextMessage sessiond:" + session.getId() + "\tmessage:" + msg + "\t" + ssoUser.getUserName());
        if(msg.startsWith("LIVECONNECT")){//网页连接websocket，传递chatSessionId
            try {//msg:LIVECONNECT 5
                String[] msgArr = msg.split("\\s+");
                if(msgArr.length == 2 && ssoUser != null){
                    Integer chatSid = Integer.parseInt(msgArr[1]);
                    logger.info("begin to addSession:" + chatSid);
                    adapter.addUserSession(ssoUser, chatSid, session);
                }else{
                    logger.error("splited:" + msgArr.length + "\t" + ssoUser);
                }
            }catch (Exception e){
                logger.info("【异常-处理消息】[ChatHandler][handleTextMessage]LIVECONNECT出现异常"+e);
            }
        }
        super.handleTextMessage(session, message);
    }

    /**
     * js上载了附件
     * @param session
     * @param message
     * @throws Exception
     */
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
        logger.info(message);
    }


    public boolean supportsPartialMessages() {
        return true;
    }


}
